<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-input-search v-model="search" placeholder="输入资源路径或者资源地址" @search="$refs.table.refresh(true)" style="width: 300px; margin-bottom:30px; margin-right: 20px"/>
      <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      <a-table :data-source="data" :columns="columns" @change="handleTableChange">
        <div
          slot="filterDropdown"
          slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
          style="padding: 8px"
        >
          <a-input
            v-ant-ref="c => (searchInput = c)"
            :placeholder="`Search ${column.dataIndex}`"
            :value="selectedKeys[0]"
            style="width: 188px; margin-bottom: 8px; display: block;"
            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
            @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
          />
          <a-button
            type="primary"
            icon="search"
            size="small"
            style="width: 90px; margin-right: 8px"
            @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
          >
            Search
          </a-button>
          <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
            Reset
          </a-button>
        </div>
        <a-icon
          slot="filterIcon"
          slot-scope="filtered"
          type="search"
          :style="{ color: filtered ? '#108ee9' : undefined }"
        />
        <template slot="customRender" slot-scope="text, record, index, column">
          <span v-if="searchText && searchedColumn === column.dataIndex">
            <template
              v-for="(fragment, i) in text
                .toString()
                .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
            >
              <mark
                v-if="fragment.toLowerCase() === searchText.toLowerCase()"
                :key="i"
                class="highlight"
              >{{ fragment }}</mark
              >
              <template v-else>{{ fragment }}</template>
            </template>
          </span>
          <template v-else>
            {{ text }}
          </template>
        </template>
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleDel(record)">删除</a>
          </template>
        </span>
      </a-table>
    </div>
  </a-card>
</template>

<script>
import request from '@/utils/request'

const qs = require('qs')
const queryData = params => {
  return request({
    url: '/alpha-common/resources',
    method: 'get',
    params: params,
    paramsSerializer: params => {
      return qs.stringify(params, { arrayFormat: 'repeat' })
    }
  })
}
export default {
  data () {
    return {
      data: [],
      search: null,
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      columns: [
        {
          title: '资源名称',
          dataIndex: 'name',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          },
          onFilter: (value, record) =>
            record.name
              .toString()
              .toLowerCase()
              .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              })
            }
          }
        },
        {
          title: '资源地址',
          dataIndex: 'url',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender'
          },
          onFilter: (value, record) =>
            record.url
              .toString()
              .toLowerCase()
              .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: visible => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              })
            }
          }
        },
        {
          title: '请求方法',
          dataIndex: 'method',
          filters: [
            { text: 'GET', value: 'GET' },
            { text: 'POST', value: 'POST' },
            { text: 'PUT', value: 'PUT' },
            { text: 'DELETE', value: 'DELETE' }
          ]
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          sorter: true
        },
        {
          title: '创建人',
          dataIndex: 'createdBy'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },
  mounted () {
    this.fetch()
  },
  methods: {
    handleSearch (selectedKeys, confirm, dataIndex) {
      confirm()
      this.searchText = selectedKeys[0]
      this.searchedColumn = dataIndex
      // const search = {}
      // search[dataIndex + '~'] = selectedKeys[0]
      // this.fetch(search)
    },

    handleReset (clearFilters) {
      clearFilters()
      this.searchText = ''
      // this.fetch()
    },

    handleTableChange (pagination, filters, sorter) {
      console.log('pagination', pagination)
      console.log('filters', filters)
      console.log('sorter', sorter)
      const pager = { ...this.pagination }
      this.current = pagination.current
      this.pagination = pager
      const orders = (sorter && sorter.order) ? { orders: (sorter.order === 'ascend') ? sorter.field : '-' + sorter.field } : {}
      const search = {}
      if (this.searchText) {
        filters[this.searchedColumn] = undefined
        search[this.searchedColumn + '~'] = this.searchText
      }
      this.fetch({
        size: pagination.pageSize,
        current: pagination.current,
        search: this.search,
        ...search,
        ...orders,
        // sortOrder: sorter.order,
        ...filters
      })
    },
    fetch (params = {}) {
      this.loading = true
      queryData({
        ...params
      }).then(({ data }) => {
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.loading = false
        this.data = data.records
        this.pagination = pagination
      })
    }
  }
}
</script>
<style scoped>
.highlight {
  background-color: rgb(255, 192, 105);
  padding: 0px;
}
</style>
